package com.vhall.component.framework.oss.client;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.vhall.component.framework.common.exception.ErrorCode;
import com.vhall.component.framework.common.model.Result;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.util.Assert;

/**
 * 扩展类,
 *
 * @author yongzheng.xu
 * @date 2021/5/22 21:26
 */
@Data
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class OssResult<T> extends Result<T> {

    /**
     * API 返回错误码
     * <p>
     * 由于第三方的错误码可能是字符串，所以使用 String 类型
     */
    @JsonProperty("api_code")
    private String apiCode;
    /**
     * API 返回提示
     */
    @JsonProperty("api_msg")
    private String apiMsg;

    /**
     * API 请求编号
     */
    @JsonProperty("api_request_id")
    private String apiRequestId;

    private OssResult() {
    }

    public static <T> OssResult<T> build(String apiCode, String apiMsg, String apiRequestId,
                                         T data, OssCodeMapping codeMapping) {
        Assert.notNull(codeMapping, "参数 codeMapping 不能为空");
        OssResult<T> result = new OssResult<>();
        result.setApiCode(apiCode);
        result.setApiMsg(apiMsg);
        result.setApiRequestId(apiRequestId);
        result.setData(data);

        // 翻译错误码
        ErrorCode errorCode = codeMapping.apply(apiCode);
        if (errorCode == null) {
            errorCode = OssErrorCode.UNKNOWN;
        }
        result.setCode(errorCode.getCode());
        result.setMsg(errorCode.getMsg());
        return result;
    }

    public static <T> OssResult<T> error(Throwable ex) {
        OssResult<T> result = new OssResult<>();
        result.setCode(OssErrorCode.EXCEPTION.getCode());
        result.setMsg(ExceptionUtil.getRootCauseMessage(ex));
        return result;
    }
}
